﻿using System;
using Microsoft.Win32;

namespace BrowserMaster
{
    public class Registrar
    {
        #region Methods

        public static void Register(string protocol, string handlerPath, string iconPath)
        {
            var root = Registry.ClassesRoot;
            //var root = Registry.CurrentUser.OpenSubKey(@"Software\Classes\", true);

            Register(root, protocol, handlerPath, iconPath);
        }

        public static void Register(RegistryKey root, string protocol, string handlerPath, string iconPath)
        {
            protocol = protocol.ToLower();

            // If this key already exists delete it so we start fresh
            root.DeleteSubKeyTree(protocol);
         
            RegistryKey protocolKey = root.CreateSubKey(protocol);
            protocolKey.SetValue(@"URL Protocol", string.Empty, RegistryValueKind.String);
            protocolKey.SetValue(string.Empty, @"URL:HyperText Transfer Protocol");

            RegistryKey cmdKey = OpenOrCreateSubKey(protocolKey, @"shell\open\command");
            cmdKey.SetValue(string.Empty, handlerPath);

            if (string.IsNullOrEmpty(iconPath)) return;
            RegistryKey iconKey = OpenOrCreateSubKey(protocolKey, @"DefaultIcon");
            iconKey.SetValue(string.Empty, iconPath);
        }

        /// <summary>
        /// Registers the application at the path specified as the default browser.
        /// </summary>
        /// <param name="path">The path to the browser with the arguments specified</param>
        public static void RegisterBrowser(string path, string iconPath)
        {
            if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
            if (!path.Contains(@"%1")) throw new ArgumentException("Path must specify the full argument list and contain %1 to represent passed in arguments");
            Register("http", path, iconPath);
            Register("https", path, iconPath);
        }

        #endregion

        #region Helpers
        private static RegistryKey OpenOrCreateSubKey(RegistryKey baseKey, string subKeyPath)
        {
            return baseKey.OpenSubKey(subKeyPath, true) ?? baseKey.CreateSubKey(subKeyPath);
        }
        #endregion
    }
}
